var JWT = require('../public/javascripts/jwt');
var express = require('express');
var router = express.Router();
const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../uploads'));
  },
  filename: (req, file, cb) => {
    const extentName = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + Date.now() + extentName);
  },
})
// 限制大小
const limits = {
  fileSize: 1024*1024*5
}
// 限制类型
const fileFilter = (req, file, cb) => {
  // 限制文件上传类型，仅可上传png格式图片
  if(file.mimetype == 'image/png' || file.mimetype === 'image/jpeg'){
    cb(null, true);
  } else {
    cb(null, false);
  }
}
const upload = multer({ storage, limits, fileFilter })

const getTokenInfo = (token) => {
  const tokenInfo = JWT.verifyToken(token.split(' ')[1]);
  console.log(tokenInfo)
}

/* 图片上传. */
router.post('/image', upload.single('file'), function(req, res, next) {
  // console.log(req.body);
  // getTokenInfo(req.get('Authorization'));
  if (req.file) {
    res.send({
      code: 200,
      data: '/uploads/' + req.file.filename,
      msg: '上传成功'
    });
  } else {
    res.status(500);
    res.send({
      code: 500,
      msg: '上传失败，文件类型为png/jpg'
    })
  }
});


module.exports = router;
